<template>
  <el-drawer direction="rtl"  :title="dialogTitle" v-model="dialogVisible" size="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="中间件" prop="netSysId"> 
        <el-select
              v-model="formData.netSysId"
              placeholder="中间件"
              class="!w-240px"
            >
              <el-option
                v-for="n in sysConfigList"
                :key="n.id"
                :label="n.community.name"
                :value="n.id"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="房产地址" prop="houseName">
          <el-input v-model="formData.houseName" :readonly="true">
            <template #append>
              <el-button icon="el-icon-search" @click="selectHouse()">选择</el-button>
              <el-button type="success" @click="closeHouse()">清空</el-button>
            </template>
          </el-input>
      </el-form-item>
      <el-form-item label="分账模式" prop="divideMode">
        <el-select
              v-model="formData.divideMode"
              placeholder="分账模式"
              class="!w-240px"
              @change="triggerDivide"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.NET_DIVIDE_MODE)"
                :key="parseInt(dict.value)"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="设置说明" v-if="formData.divideMode != undefined">
        <div v-if="formData.divideMode == 0" style="color: green;">注意：若设置了分账账户1，则扣除手续费后的金额会自动进入兜底账户</div>
        <div v-if="formData.divideMode == 1" style="color: red;">设置房东/抽成人员分成比例即可，剩余比例会自动进入兜底账户</div>
        <div v-if="formData.divideMode == 2" style="color: blue;">设置房东/抽成人员分成金额即可，剩余金额会自动进入兜底账户</div>
      </el-form-item>

      <el-row v-if="showMatCode1Flag">
        <el-col :span="12">
          <el-form-item label="分账账户1" prop="divideMatId1">
            <el-input v-model="formData.divideMatUserName1_" :readonly="true">
              <template #append>
                <el-button icon="el-icon-search" @click="openMat('divideMatId1')">选择</el-button>
                <el-button type="success" @click="clearMat('divideMatId1')">清空</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="matValueRemarkLabel" prop="divideMatValue1">
            <el-input v-model="formData.divideMatValue1" placeholder="请输入值1">
              <template #append>
                <el-button >{{  matValueAppendRemarkLabel }}</el-button>
                <el-button type="success" @click="clearMat('divideMatValue1')">清空</el-button></template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="showMatCode2Flag">
        <el-col :span="12">
          <el-form-item label="分账账户2" prop="matCodeId2">
            <el-input v-model="formData.divideMatUserName2_" :readonly="true">
              <template #append>
                <el-button icon="el-icon-search" @click="openMat('divideMatId2')">选择</el-button>
                <el-button type="success" @click="clearMat('divideMatId2')">清空</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="matValueRemarkLabel" prop="divideMatValue2">
            <el-input v-model="formData.divideMatValue2" placeholder="请输入值2">
              <template #append>
                <el-button >{{  matValueAppendRemarkLabel }}</el-button>
                <el-button type="success" @click="clearMat('divideMatValue2')">清空</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="12">
          <el-form-item style="color:red;" label="兜底账户" prop="underTakeMatCode">
            <el-input v-model="formData.underTakeMatName_" placeholder="请输入兜底账户">
              <template #append>
                <el-button icon="el-icon-search" @click="openMat('underTakeMatCode')">选择</el-button>
                <el-button type="success" @click="clearMat('underTakeMatCode')">清空</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="说明" prop="mateValue2">
            <span style="color:red;">扣除手续费+分账账户1+分账账户2 后的余额进入该兜底账户</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>  

  <HouseSelect
    ref="houseSelectRef"
    @confirm-house="confirmHouse"
  />

  <OwnMeterConfigSelect
    ref="ownMeterConfigSelectRef"
    @confirm-own-meter-config="confirmOwnMeterConfig"
  />

  
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { NetHouseAccountMapApi, NetHouseAccountMapVO } from '@/api/zwsj/nethouseaccountmap'
import { getNetSysConfigs } from '@/api/zwsj/netSysConfig'
import OwnMeterConfigSelect from '@/views/zwsj/common/OwnMeterConfigSelect.vue'
import HouseSelect from '@/views/zwsj/common/HouseSelect.vue'

/** 宽带分账配置（房产） 表单 */
defineOptions({ name: 'NetHouseAccountMapForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const showMatCode1Flag = ref(false)
const showMatCode2Flag = ref(false)
const matValueRemarkLabel = ref('')
const matValueAppendRemarkLabel = ref('')

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  netSysId: undefined,
  houseId: undefined,
  houseName: undefined,
  divideMode: undefined,
  divideMatUserName1_: undefined,
  divideMatId1: undefined,
  divideMatCode1_: undefined,
  divideMatValue1: undefined,
  divideMatUserName2_: undefined,
  divideMatId2: undefined,
  divideMatCode2_: undefined,
  divideMatValue2: undefined,
  underTakeMatCode: undefined,
  underTakeMatName_: undefined
})
const formRules = reactive({
  netSysId: [{ required: true, message: '中间件不能为空', trigger: 'blur' }],
  houseId: [{ required: true, message: '房产ID不能为空', trigger: 'blur' }],
  houseName: [{ required: true, message: '房产地址不能为空', trigger: 'blur' }],
  divideMode: [{ required: true, message: '分账模式（0单账户 1多账户比例分账 2多账户金额分账）不能为空', trigger: 'change' }],
  underTakeMatCode: [{ required: true, message: '兜底账户编码不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const sysConfigList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await NetHouseAccountMapApi.getNetHouseAccountMap(id)
      triggerDivide()
    } finally {
      formLoading.value = false
    }
  }
  sysConfigList.value = await getNetSysConfigs()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as NetHouseAccountMapApi.NetHouseAccountMapVO
    if (formType.value === 'create') {
      await NetHouseAccountMapApi.createNetHouseAccountMap(data)
      message.success(t('common.createSuccess'))
    } else {
      await NetHouseAccountMapApi.updateNetHouseAccountMap(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    netSysId: undefined,
    houseId: undefined,
    houseName: undefined,
    divideMode: undefined,
    divideMatUserName1_: undefined,
    divideMatId1: undefined,
    divideMatCode1_: undefined,
    divideMatValue1: undefined,
    divideMatUserName2_: undefined,
    divideMatId2: undefined,
    divideMatCode2_: undefined,
    divideMatValue2: undefined,
    underTakeMatCode: undefined,
    underTakeMatName_: undefined
  }
  formRef.value?.resetFields()
}


// 选择分账功能
const ownMeterConfigSelectRef = ref()
const openMat = async (flag) => {
  ownMeterConfigSelectRef.value.open(flag)
}
const confirmOwnMeterConfig = async ({matCode,flag}) => {
  if(flag !+ undefined && flag != null){
    if(flag == "divideMatId1"){
      formData.value.divideMatUserName1_ = matCode.configRemark
      formData.value.divideMatId1 = matCode.id
      formData.value.divideMatCode1_ = matCode.matCode
    }else if(flag == "divideMatId2"){
      formData.value.divideMatUserName2_ = matCode.configRemark
      formData.value.divideMatId2 = matCode.id
      formData.value.divideMatCode2_ = matCode.matCode
    }else if(flag == "underTakeMatCode"){
      formData.value.underTakeMatName_ = matCode.configRemark
      formData.value.underTakeMatCode = matCode.matCode
    }
  }
}
const clearMat = async (flag) => {
  if(flag !+ undefined && flag != null){
    if(flag == "divideMatId1"){
      formData.value.divideMatUserName1_ = undefined
      formData.value.divideMatId1 = undefined
      formData.value.divideMatCode1_ = undefined
    }else if(flag == "divideMatId2"){
      formData.value.divideMatUserName2_ = undefined
      formData.value.divideMatId2 = undefined
      formData.value.divideMatCode2_ = undefined
    }else if(flag == "underTakeMatCode"){
      formData.value.underTakeMatName_ = undefined
      formData.value.underTakeMatCode = undefined
    }else if(flag == "divideMatValue1"){
      formData.value.divideMatValue1 = undefined
    }else if(flag == "divideMatValue2"){
      formData.value.divideMatValue2 = undefined
    }
  }
}

const triggerDivide = async() => {
  let divideMode = (formData.value.divideMode)
  if(divideMode == 0){
    //清空账户1、2的内容，并显示兜底账户
    // formData.value.divideMatUserName1_ = undefined
    // formData.value.divideMatId1 = undefined
    // formData.value.divideMatCode1_ = undefined
    formData.value.divideMatUserName2_ = undefined
    formData.value.divideMatId2 = undefined
    formData.value.divideMatCode2_ = undefined

    showMatCode1Flag.value = true
    matValueRemarkLabel.value = '比例'
    matValueAppendRemarkLabel.value = '%'

    showMatCode1Flag.value = true
    showMatCode2Flag.value = false
  }else if(divideMode == 1){
    showMatCode1Flag.value = true
    showMatCode2Flag.value = true
    matValueRemarkLabel.value = '比例'
    matValueAppendRemarkLabel.value = '%'
  }else if(divideMode == 2){
    showMatCode1Flag.value = true
    showMatCode2Flag.value = true
    matValueRemarkLabel.value = '金额'
    matValueAppendRemarkLabel.value = '元'
  }

  // //查询出兜底账户
  // let underTakeMatConfig = await NetHouseAccountMapApi.getNetUnderTakeMat(divideMode)
  // formData.value.underTakeMatCode = underTakeMatConfig.underTakeMatCode || ""
}

// 选择分账功能
const houseSelectRef = ref()
const selectHouse = async () => {
  houseSelectRef.value.open()
}
const closeHouse = async () => {
    formData.value.houseName = undefined
    formData.value.houseId = undefined
}
const confirmHouse = async (house: any) => {
    formData.value.houseName = house.name
    formData.value.houseId = house.id
}

 
</script>